angular.module('Controller')

.controller('QgyHouseDetailCtrl', ($scope,NgTableParams,menuManage,wfAlert,$localStorage,commonUtil,commonConstant,$rootScope,$uibModal,$http) ->
    if $rootScope.pageType=='house-detail'
        #接受数据:{houseId,contractId,house,contract}
        data=angular.copy($rootScope.pageParams)
        $scope.houseId=data.houseId
        $scope.house=data.house
        $scope.contractId=data.contractId
        $scope.contract=data.contract
        $rootScope.pageParams=undefined
        $rootScope.pageType=undefined
    $scope.housePayTypeList=commonConstant.payWayList();
    $scope.allPayTypeList=commonConstant.allPayTypeList()
    loadData=()->
        return if $scope.houseId==undefined
        ##因不同页面进入房间详情时，可能缺少房间明细或相关合同信息，在本处按各情况一一处理
        if $scope.house==undefined
            loadHouse($scope.houseId)
        else if $scope.house.status==2 || $scope.house.status==8
            if $scope.contractId==undefined
                loadContractByHouse($scope.houseId)
            else if $scope.contractId>=0 and $scope.contract==undefined
                loadContractById($scope.contractId)
    loadHouse=(id)->
        return if id==undefined
        $http.get("/house/#{id}/detail")
        .success((resp)->
            if resp.code==0
                $scope.house=resp.message
                if $scope.house.status==2 || $scope.house.status==8
                    if $scope.contractId==undefined
                        loadContractByHouse($scope.houseId)
                    else if $scope.contractId>=0 and $scope.contract==undefined
                        loadContractById($scope.contractId)
        )
    loadContractByHouse=(houseId)->
        $http.get("/contract/house/#{houseId}/statusInfo")
        .success((resp)->
            if resp.code==0
                $scope.contractId=resp.message.contractId
                $scope.house.depositBillId=resp.message.depositBillId
                if $scope.contractId>=0
                    loadContractById($scope.contractId)
                else if $scope.house.status==8
                    loadEarnestData($scope.houseId)
        )
    loadContractById=(contractId)->
        $http.get("/contract/#{contractId}/detail")
        .success((resp)->
            if resp.code==0
                $scope.contract=resp.message
                $scope.contract.cotenants=[] if $scope.contract.cotenants==undefined
        )
    loadEarnestData=(houseId)->
        reqData={houseId:houseId,page:0,size:999}
        $http.get("/earnest",params:reqData)
        .success((resp)->
            if resp.code==0 and resp.message.content.length==1
                $scope.earnest=resp.message.content[0]
        )
    $scope.refreshData=()->
        updateData()
    updateData=()->
        $scope.needRefresh=false
        $scope.contract=undefined
        $scope.contractId=undefined
        $scope.earnest=undefined
        loadHouse($scope.houseId)
    loadData()
    $scope.sexList=commonConstant.qgySexList()
    _.extend $scope,
        openCotenant:(type,item)->
            modal=showCotenantModal(type,item)
            modal.result.then((modalData)->
                if modalData && type!='view'
                    item=modalData
            )
            ''
        doRelet:()->
            $rootScope.pageType='relet-check-in'
            $rootScope.pageParams=angular.copy({house:$scope.house,contract:$scope.contract})
            menuManage.goState('relet-check-in',true)
        doOffCheckIn:()->
            $rootScope.pageType='offline-check'
            $rootScope.pageParams={house:angular.copy($scope.house)}
            menuManage.goState('offline-check-in',true)
        doOnCheckIn:()->
            $rootScope.pageType='online-check'
            $rootScope.pageParams=angular.copy({contractId:$scope.contractId})
            menuManage.goState('online-check-in',true)
        doSublet:()->
            $rootScope.pageType='sublet-check-in'
            $rootScope.pageParams=angular.copy({house:$scope.house,contract:$scope.contract})
            menuManage.goState('sublet-check-in',true)
        isRenting:()->
            $scope.house.status==2 && $scope.contract?.status==8
        showLeaseInfo:()->
            if $scope.contract.status==8
                if !$scope.contract.nextLeaseTime
                    return '(账单已缴清)'
                else
                    nextLease=moment($scope.contract.nextLeaseTime)
                    if nextLease.diff(moment(),'days')<0
                        return '已欠费'+Math.abs(nextLease.diff(moment(),'days'))+'天'
                    else
                        return '距离下次缴租日期还有'+nextLease.diff(moment(),'days')+'天'
            else
                ''

        doOffLease:()->
            $rootScope.pageType='off-lease-confirm'
            data={
                houseId:$scope.houseId
                house:$scope.house
                contractId:$scope.contractId
                contract:$scope.contract
            }
            $rootScope.pageParams=data
            menuManage.goState('off-lease-confirm',true)
        changeHouse:()->
            $rootScope.pageType='change-house-check-in'
            $rootScope.pageParams=angular.copy({house:$scope.house,contract:$scope.contract})
            menuManage.goState('change-house-check-in',true)
        payLease:()->
            $http.get('/bill',params:{page:0,size:999,type:1,contractId:$scope.contract.id,status:1})
            .success((resp)->
                if resp.code==0
                    if resp.message.content.length>0 and resp.message.content[0].status==1
                        $scope.recentLeaseBill=resp.message.content[0]
                        showBillModal('',angular.copy($scope.recentLeaseBill))
                    else
                        updateData()
                        wfAlert.toastInfo('房租账单已全部支付')
                        return
                else
                    wfAlert.toastError(resp.message)
            )
        goContractDetail:()->
            ''
        rechargePower:()->
            showPowerModal('',angular.copy($scope.contract))
        doEarnest:()->
            showEarnestModal('edit',angular.copy($scope.house))
        earnestCheckIn:()->
            reqData={houseId:$scope.houseId,page:0,size:999}
            $http.get("/earnest",params:reqData)
            .success((resp)->
                if resp.code==0 and resp.message.content.length==1
                    $rootScope.pageType='offline-check'
                    data={
                        earnest:resp.message.content[0]
                        house:$scope.house
                    }
                    $rootScope.pageParams=data
                    menuManage.goState('offline-check-in',true)
                else
                    wfAlert.toastError('定金信息获取失败')
                    updateData()
            )
        printContract:()->
            cnt=$scope.contract
            if cnt and cnt.contractPdf
                window.open(cnt.contractPdf, '_blank')
            else
                wfAlert.toastError('合同pdf文件未生成')
            ''
#        warnSMS:(item)->
#            smsText=item.apartmentName+'房间:'+item.houseNo+'从'+
#                    moment(item.startTime).format('YYYY年MM月DD日')+'至'+
#                    moment(item.endTime).format('YYYY年MM月DD日')+'的租金账单已生成，付费截止时间：'+
#                    moment(item.startTime).format('YYYY年MM月DD日')+'。请在付费截止时间之前及时支付租金，谢谢您的支持。'
#            str='确认向用户发送催款信息【'+smsText+'】吗？'
#            return str
#        doPress:()->
#            $http.post("/bill/#{item.id}/sms")
#            .success((resp)->
#                if resp.code==0
#                    wfAlert.toastInfo('催款通知已发送')
#            )
#            ''
        doRevokeContract:()->
            if $scope.contract?.status!=2
                wfAlert.toastError('合同状态异常')
                updateData()
                return
            theData=angular.copy($scope.contract)
            showRevokeModal('',theData)
        needWarn:()->
            if $scope.contract.nextLeaseTime
                return moment($scope.contract.nextLeaseTime).diff(moment(),'days') <= 5
            else
                return false
        noOwningBill:()->
            !$scope.contract.nextLeaseTime || moment($scope.contract.nextLeaseTime).diff(moment(),'days') >=0
    showCotenantModal=(type,data)->
        modal = $uibModal.open({
            animation: true,
            size:'lg',
            appendTo: $("#modalContent:eq(0)"),
            controller: 'QgyCotenantModalCtrl',
            templateUrl: 'templates/business-manage/cotenant-modal/cotenant-modal.html',
            resolve: {
                items:  ()->{type:type,data:data}
            }
        })
    showRevokeModal=(type,data)->
        modal = $uibModal.open({
            animation: true,
            size:'lg',
            appendTo: $("#modalContent:eq(0)"),
            controller: 'QgyRevokeContractModalCtrl',
            templateUrl: 'templates/house-manage/revoke-contract-modal/revoke-contract-modal.html',
            resolve: {
                items:  ()->{type:type,data:data}
            }
        })
    showBillModal=(type,data)->
        $scope.modal = $uibModal.open({
            animation: true,
            appendTo: $("#modalContent:eq(0)"),
            controller: 'QgyRentPayModalCtrl',
            templateUrl: 'templates/business-manage/rent-pay-modal/rent-pay-modal.html',
            resolve: {
                items:  ()->{type: type, data: data}
            }
        })
        $scope.modal.result.then((modalData)->
            ''
        )
    showPowerModal=(type,data)->
        $scope.modal = $uibModal.open({
            animation: true,
            appendTo: $("#modalContent:eq(0)"),
            controller: 'QgyPowerPayModalCtrl',
            templateUrl: 'templates/business-manage/power-pay-modal/power-pay-modal.html',
            resolve: {
                items:  ()->{type: type, data: data}
            }
        })
        $scope.modal.result.then((modalData)->
            loadContractById($scope.contractId)
        )
    showEarnestModal=(type,data)->
        $scope.modal = $uibModal.open({
            animation: true,
            size:'lg',
            appendTo: $("#modalContent:eq(0)"),
            controller: 'QgyPayEarnestModalCtrl',
            templateUrl: 'templates/house-manage/pay-earnest/pay-earnest-modal.html',
            resolve: {
                items:  ()->{type: type, data: data}
            }
        })
        $scope.modal.result.then((modalData)->
            $rootScope.$broadcast('refresh')
            updateData()
        )
    $rootScope.$on('refresh',(info)->
        if $scope.needRefresh!=true
            $scope.needRefresh=true
    )
    $rootScope.$watch('navTabs.active',(href)->
        if(href=='house-detail' && $scope.needRefresh)
            updateData()
    )
)